<template>
  <el-dialog
    title="上传文件"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-upload
      drag
      :action="url"
      :before-upload="beforeUploadHandle"
      :on-success="successHandle"
      multiple
      :file-list="fileList"
      style="text-align: center;">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只支持jpg、png、gif格式的图片！</div>
    </el-upload>
  </el-dialog>
</template>

<script>
  import Cookies from 'js-cookie'
  export default {
    data () {
      return {
        visible: false,
        url: '',
        num: 0,
        fileList: []
      }
    },
    methods: {
      init () {
        this.url = `${window.SITE_CONFIG['baseURL']}/sys/oss/upload?token=${Cookies.get('token')}`
        this.num = 0
        this.fileList = []
        this.visible = true
      },
      // 上传之前
      beforeUploadHandle (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
        this.num++
      },
      // 上传成功
      successHandle (response, file, fileList) {
        if (response && response.code === 0) {
          this.fileList = fileList
          this.num--
          if (this.num === 0) {
            this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
          }
        } else {
          this.$message.error(response.msg)
        }
      }
    }
  }
</script>
